﻿using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;

namespace MessageSystem
{
    /// <summary>
    /// 消息终端
    /// </summary>
    public class MessageTerminal : MonoBehaviour, IMessageTerminal
    {
        /// <summary>
        /// 消息缓存
        /// </summary>
        Dictionary<string, Action<IMessageArgs>> messageDict = new Dictionary<string, Action<IMessageArgs>>();
        /// <summary>
        /// 终端ID
        /// </summary>
        public int ID { get; set; }

        private bool isActive;

        /// <summary>
        /// 获取终端注册的所有消息
        /// </summary>
        public string[] Messages
        {
            get
            {
                string[] messages = new string[messageDict.Count];
                messageDict.Keys.CopyTo(messages, 0);
                return messages;
            }
        }

        #region Unity 生命周期

        void OnEnable()
        {
            isActive = true;
        }

        void Start()
        {

        }

        void Update()
        {

        }
        void OnDisable()
        {
            isActive = false;
        }

        void OnDestroy()
        {
            MessageSystemFacade.Inst.UnRegisterMessageTerminal(this);
        }
        #endregion


        /// <summary>
        /// 消息注册
        /// </summary>
        /// <param name="messageType">消息类型</param>
        /// <param name="onMessage">收到消息的回调</param>
        public void RegisterMessage(string messageType, Action<IMessageArgs> onMessage)
        {
            if (!messageDict.ContainsKey(messageType))
            {
                messageDict.Add(messageType, onMessage);
                MessageSystemFacade.Inst.RegisterMessage(messageType, this);
            }
            else
            {
                DebugUtils.LogRedInfo("重复注册" + messageType);
            }
        }

        /// <summary>
        /// 注销消息
        /// </summary>
        /// <param name="messageType"></param>
        public void UnRegisterMessage(string messageType)
        {
            if (messageDict.ContainsKey(messageType))
            {
                messageDict.Remove(messageType);
                MessageSystemFacade.Inst.UnRegisterMessage(messageType, this);
            }
            else
            {
                DebugUtils.LogRedInfo("重复注册" + messageType);
            }
        }

        /// <summary>
        /// 接收消息
        /// </summary>
        /// <param name="messageType"></param>
        /// <param name="args"></param>
        public void ReceiveMessage(string messageType, IMessageArgs args)
        {
            if (isActive)
            {
                foreach (var item in messageDict)
                {
                    if (item.Key == messageType)
                    {
                        item.Value(args);
                    }
                }
            }
        }
    }
}

